/*
 * Copyright 2015 泛泛o0之辈
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.jfast.framework.jdbc.orm;

import java.sql.SQLException;

/**
 * Sql执行器
 */
public abstract class Executor extends Parser{

    /**
     * Sql执行
     * @return
     * @throws SQLException
     * @throws IllegalAccessException
     * @throws NoSuchFieldException
     * @throws InstantiationException
     */
    public Object execute() throws SQLException, IllegalAccessException, NoSuchFieldException, InstantiationException {
        Object reObj = null;
        ps = conn.prepareStatement(parseSql());
        fillPreparedStatement();
        if(returnType == void.class)
            ps.executeUpdate();
        else if(returnType == Boolean.class || returnType == Boolean.TYPE)
            reObj = ps.execute();
        else if(returnType == Integer.class || returnType == Integer.TYPE)
            reObj = ps.executeUpdate();
        else
            throw new RuntimeException("不支持的返回类型:"+method.getReturnType());
        if(conn.getAutoCommit() == true && !conn.isClosed())
            conn.close();
        return reObj;
    }

    /**
     * 对PreparedStatement赋值
     */
    public void fillPreparedStatement() throws SQLException {
       for(int i = 1; i<=sqlFields.size(); i++){
           ps.setObject(i,paramMaps.get(sqlFields.get(i-1).toLowerCase()));
       }
    }
}
